#!/usr/bin/python
import sys, re, os, subprocess, random

def get_output(cmd):
    '''a little wrapper around subprocess.Popen'''
    print 'RUNNING: '+(' '.join(cmd))
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    p.wait()
    if p.returncode != 0:
        raise 'subprocess returned: %d' % p.returncode
    return p.stdout

def run(cmd):
    '''a little wrapper around check_call'''
    print 'RUNNING: '+(' '.join(cmd))
    return subprocess.check_call(cmd)

# it goes a little something like this
# TMPBRANCH=merge-rand()
# CURRENTBRANCH=git-svn-checkin-TMPBRANCH
# git checkout -b TMPBRANCH remotes/git-svn
# git merge --squash CURRENTBRANCH
# git commit
# git-svn dcommit
# git checkout CURRENTBRANCH
# git branch -d TMPBRANCH

branch = None
for line in get_output(['git-branch']).readlines():
    m = re.match(r'^\* (?P<branch>\w+)\s*$', line)
    if m:
        branch = m.groupdict()['branch']
        break

if branch == None:
    print "I can't work out what the current branch is"
    sys.exit(1)

tmpbranch = 'git-svn-checkin-%s' % branch

run(['git-checkout', '-b', tmpbranch, 'remotes/git-svn'])

run(['git-merge', '--squash', branch])

run(['git-commit'])

run(['git-svn', 'dcommit'])

run(['git-checkout', branch])

run(['git-branch', '-D', tmpbranch])
